package com.idea.zd.sys.train.jms;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * 消息生产者
 */
public class Provider {

    private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
    private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
    private static final String BROKERURL = ActiveMQConnection.DEFAULT_BROKER_URL;

    //客户端用来创建连接的受管对象
    private  ConnectionFactory connectionFactory;

    //客户端到JSM提供者之间活动连接
    private  Connection connection;

    //发送和接收消息的一个单线程上下文
    private  Session session;

    //目的地
    private Destination destination;

    /**
     * 初始连接方法
     */
    public void init(){
        try {
            //工厂实现
            connectionFactory = new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKERURL);
            //创建jsm连接
            connection = connectionFactory.createConnection();
            //开启连接
            connection.start();
            //创建session
            session = connection.createSession(true,Session.SESSION_TRANSACTED);
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送方法
     * @param disName
     */
    public void sendMessage(String disName){

        try {
            //创建对列
            destination = session.createQueue(disName);
            //创建生产者
            MessageProducer messageProducer = session.createProducer(destination);

            for(int i =0;i <100;i++){
                //消息对象
                TextMessage textMessage= session.createTextMessage("第"+(i+1)+"个消息！");
                System.out.println("第"+(i+1)+"个消息！");
                //发送、加入消息
                messageProducer.send(textMessage);
                //提交
                session.commit();
            }

        } catch (JMSException e) {
            e.printStackTrace();
        }finally {
            if(null !=connection){
                try {
                    connection.close();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String [] args){
        /*Provider provider = new Provider();
        provider.init();
        provider.sendMessage("sms_10");*/

        Consumer consumer = new Consumer();
        consumer.init();
        consumer.getMessage("sms_10");

    }
}
